package hot.job.core.factory;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.leader.LeaderLatch;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * leader latch factory class
 * @author gaowenhao
 * @since 2022/7/4 21:30
 */
public class LeaderLatchFactory {

    private final CuratorFramework defClient;

    private final Map<String, LeaderLatch> cacheMap = new HashMap<>();

    public LeaderLatchFactory(CuratorFramework defClient){
        this.defClient = defClient;
    }

    public LeaderLatch createLatch(CuratorFramework client, String path){
        return getLeaderLatch(path, client);
    }

    public LeaderLatch createLatch(String path){
        return getLeaderLatch(path, this.defClient);
    }

    private LeaderLatch getLeaderLatch(String path, CuratorFramework defClient) {
        LeaderLatch latch = new LeaderLatch(defClient, path);
        this.cacheMap.put(path, latch);
        return latch;
    }

    public LeaderLatch getLatch(String path){
        return this.cacheMap.get(path);
    }

    public Map<String, LeaderLatch> getReadableMap(){
        return Collections.unmodifiableMap(this.cacheMap);
    }


}
